package org.example.service;

import org.example.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ChatMessageService {
    private static final Logger logger = LoggerFactory.getLogger(ChatMessageService.class);
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    /**
     * 保存聊天消息到MongoDB
     */
    public void saveMessage(ChatMessage message) {
        try {
            // 设置创建时间
            message.setCreatedAt(new Date());
            
            // 保存到MongoDB
            mongoTemplate.save(message, "chat_messages");
            logger.info("消息已保存到MongoDB: {}", message.getContent());
        } catch (Exception e) {
            logger.error("保存消息到MongoDB失败", e);
            throw new RuntimeException("保存消息失败", e);
        }
    }
    
    /**
     * 获取用户的历史消息
     */
    public List<ChatMessage> getHistoryMessages(String username) {
        Query query = new Query(
            new Criteria().orOperator(
                Criteria.where("fromId").is(username),
                Criteria.where("toId").is(username)
            )
        );
        query.limit(50);  // 限制返回最近50条消息
        
        return mongoTemplate.find(query, ChatMessage.class, "chat_messages");
    }
    
    /**
     * 清除用户的历史消息
     */
    public void clearHistoryMessages(String username) {
        Query query = new Query(
            new Criteria().orOperator(
                Criteria.where("fromId").is(username),
                Criteria.where("toId").is(username)
            )
        );
        mongoTemplate.remove(query, "chat_messages");
        logger.info("已清除用户 {} 的历史消息", username);
    }
} 